package com.bee.剑指offer;

import java.util.Arrays;

/**
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2021-04-11
 */
public class 输出该数32位二进制 {

    /**
     * 获取原码
     */
    public static int[] convert32Binary(int n) {
        int[] binary = new int[32];
        int mod = 0;
        long original = n;
        if(n < 0) {
            original = -original;
        }
        for (int i = 0; i < 32; i++) {
            mod = (int)(original % 2);
            binary[31 - i] = mod;
            original /= 2;
            if(original <= 0) {
                break;
            }
        }
        if(n < 0) {
            binary[0] = 1;
        }
        System.out.println(Arrays.toString(binary));
        return binary;
    }

    /**
     * 获取负数反码
     */
    public static int[] convert32BinaryNnegativeReverse(int n) {
        int[] binary = convert32Binary(n);
        for (int i = 1; i < binary.length; i++) {
            binary[i] = binary[i] == 0 ? 1 : 0;
        }
        System.out.println(Arrays.toString(binary));
        return binary;
    }


    /**
     * 获取负数的补码
     * 在反码的基础上+1
     */
    public static int[] convert32BinaryComplement(int n) {
        int[] binary = convert32BinaryNnegativeReverse(n);
        for (int i = binary.length - 1; i > 0; i--) {
            if(binary[i] == 0) {
                binary[i] = 1;
                break;
            } else {
                binary[i] = 0;
            }
        }
        System.out.println(Arrays.toString(binary));
        return binary;
    }


    public static int NumberOf1(int n) {
        int[] binary = convert32BinaryComplement(n);
        int count = 0;
        for (int i = 0; i < binary.length; i++) {
            if(binary[i] == 1) {
                ++count;
            }
        }
        System.out.println(count);
        return count;
    }

    public static void main(String[] args) {

//        convert32Binary(-2147483648);
        NumberOf1(-2147483648);
    }

}
